#include "widget3d.h"
#include <QDebug>

#define BUFFER_OFFSET(offset) ((void*) (offset))

Widget3D::Widget3D()
{
}

Widget3D::~Widget3D()
{

}

void Widget3D::setTempRange(float HotTemp, float CoolesTemp)
{
   hotTemp = HotTemp;
   coolesTemp = CoolesTemp;
   update();
}

void Widget3D::setHottestColor(float r, float g, float b)
{
    HottestColor = QVector3D(r, g, b);
    update();
}

void Widget3D::setCoolestColor(float r, float g, float b)
{
    CoolestColor = QVector3D(r, g, b);
    update();
}

void Widget3D::initializeGL()
{
    qInfo()<<"initializeGL";
    initializeOpenGLFunctions();

//    glEnable(GL_TEXTURE_2D);

    m_program = new QOpenGLShaderProgram(this);

    m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/triangles.vert");

    m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/triangles.frag");

    m_program->link();

    //VAO，VBO数据部分
    float vertices[] = {
    //     ---- 位置 ----
         1.0f,  1.0f, 0.0f, 40.0f,
         1.0f, -1.0f, 0.0f, 20.0f,
        -1.0f, -1.0f, 0.0f, -20.0f,
        -1.0f,  1.0f, 0.0f, -40.0f,
    };

    unsigned int indices[] = { // 注意索引从0开始!
        0, 1, 3, // 第一个三角形
        1, 2, 3  // 第二个三角形
    };

    m_posAttr = m_program->attributeLocation("aPos");
    m_colorAttr = m_program->attributeLocation("VertexTemp");

    glGenVertexArrays(1, m_VAO);
    glGenBuffers(1, m_VBO);
    glGenBuffers(1, m_EBO);

    glBindVertexArray(m_VAO[0]);
    glBindBuffer(GL_ARRAY_BUFFER, m_VBO[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glVertexAttribPointer(m_posAttr, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), BUFFER_OFFSET(0));
    glVertexAttribPointer(m_colorAttr, 1, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), BUFFER_OFFSET(3 * sizeof(GLfloat)));

    glEnableVertexAttribArray(m_posAttr);
    glEnableVertexAttribArray(m_colorAttr);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void Widget3D::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);
}

void Widget3D::paintGL()
{
//    qInfo()<<"paintGL";
    glClearColor(0.2f, 0.3f, 0.3f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    m_program->bind();

    glBindVertexArray(m_VAO[0]);

    m_program->setUniformValue("CoolesTemp", coolesTemp);
    m_program->setUniformValue("TempRange", hotTemp - coolesTemp);

    m_program->setUniformValue("HottestColor", HottestColor);
    m_program->setUniformValue("CoolestColor", CoolestColor);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

    m_program->release();
}
